package org.mms.service.impl;

import org.mms.exception.BusinessException;
import org.mms.pojo.entity.User;
import org.mms.pojo.request.UserLoginRequest;
import org.mms.pojo.request.UserRegisterRequest;
import org.mms.pojo.request.UserUpdateRequest;
import org.mms.repository.UserRepository;
import org.mms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public User login(UserLoginRequest request) {
        User user = userRepository.findByUsername(request.getUsername());
        if (user == null || !user.getPassword().equals(request.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        return user;
    }

    @Override
    @CacheEvict(value = "users", allEntries = true)
    public User register(UserRegisterRequest request) {
        User existingUser = userRepository.findByUsername(request.getUsername());
        if (existingUser != null) {
            throw new BusinessException("用户名已存在");
        }
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setRole("EMPLOYEE");
        return userRepository.save(user);
    }

    @Override
    @CacheEvict(value = "users", allEntries = true)
    public User updatePassword(UserUpdateRequest request) {
        User user = userRepository.findById(request.getId())
                .orElseThrow(() -> new BusinessException("用户不存在"));
        user.setPassword(request.getPassword());
        return userRepository.save(user);
    }

    @Override
    @Cacheable(value = "users", key = "#id")
    public User getById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new BusinessException("用户不存在"));
    }

    @Override
    @Cacheable(value = "users", key = "'all'")
    public List<User> getAll() {
        return userRepository.findAll();
    }
}